//
//  FriendRequestTb.m
//  project
//
//  Created by 黄建华 on 2018/8/9.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "FriendRequestTb.h"
#import "RequestTableViewCell.h"

@implementation FriendRequestTb

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height) style:UITableViewStylePlain];
        _tableView.delegate                     = self;
        _tableView.dataSource                   = self;
        _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [self addSubview:_tableView];
        [self createMjHeader];
    }
    return self;
}

// 下拉刷新
- (void)createMjHeader
{
    _myHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadHeaderData)];
    _myHeader.backgroundColor            = [UIColor colorFromHex:0x4b4b4b];
    _myHeader.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    // 设置文字
    [_myHeader setTitle:SN_Text(@"下拉刷新") forState:MJRefreshStateIdle];
    [_myHeader setTitle:SN_Text(@"松开刷新") forState:MJRefreshStatePulling];
    [_myHeader setTitle:SN_Text(@"加载 ...") forState:MJRefreshStateRefreshing];
    
    // 设置字体
    _myHeader.stateLabel.font           = [UIFont systemFontOfSize:15];
    _myHeader.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    _myHeader.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), [[NSDate date]dateToString]];
    
    // 设置颜色
    _myHeader.stateLabel.textColor           = SNCOLORGRAY;
    _myHeader.lastUpdatedTimeLabel.textColor = SNCOLORGRAY;
    // 设置刷新控件
    _tableView.mj_header                          = _myHeader;
    _tableView.mj_header.automaticallyChangeAlpha = YES;
}

- (void)loadHeaderData {
    NSLog(@"下拉刷新>>>>>>>>");
    [self updateFriendRequest];
    [self endRefreshing:3.0 withTypte:1];
}

- (void)endRefreshing:(CGFloat)time withTypte:(NSInteger)type {
    __unsafe_unretained UITableView *tableView = self.tableView;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 结束刷新
        if (type == 1) {
            [tableView.mj_header endRefreshing];
        }
        else
        {
            [tableView.mj_footer endRefreshing];
        }
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString      *identifier = @"requestTableViewCell";
    RequestTableViewCell *cell       = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [[RequestTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    FriednInviterModel *model = _dataArray[indexPath.row];
    [cell updateCellWithModel:model];
    
    cell.okButton.tag = indexPath.row +30000;
    [cell.okButton addTarget:self action:@selector(okButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.cancelButton.tag = indexPath.row +40000;
    [cell.cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SN_Text(@"删除");
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

//点击删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    //在这里实现删除操作
    FriednInviterModel *model = _dataArray[indexPath.row];
    
    NSLog(@"要删除的  %@>>>", model.nickName);
    
    [SN_Net friendDeleteInvitation:StrByInt(model.invId) Success:^(id object) {
        [self updateFriendRequest];
    } fail:^(id object) {
    }];
    //删除数据，和删除动画
    [_dataArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
}

- (void)okButtonClick:(UIButton *)sender {
    FriednInviterModel *model = _dataArray[sender.tag - 30000];
    
    NSLog(@"同意了 %@>>>>", model.nickName);
    
    [SN_Net friendPassInvitation:StrByInt(model.invId) Success:^(id object) {
        [self updateFriendRequest];
    } fail:^(id object) {
    }];
}

- (void)cancelButtonClick:(UIButton *)sender {
    FriednInviterModel *model = _dataArray[sender.tag - 40000];
    
    NSLog(@"拒绝了 %@>>>>", model.nickName);
    [SN_Net friendRejectInvitation:StrByInt(model.invId) Success:^(id object) {
        [self updateFriendRequest];
    } fail:^(id object) {
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSLog(@"好友请求选择了>>>%d", indexPath.row);
    FriednInviterModel *model = _dataArray[indexPath.row];
    if (_selectBlock) {
        _selectBlock(model);
    }
}

- (void)updateUIViewWith:(NSArray *)array
{
//    NSLog(@"更新好友信息>>>>>%@",array);
    NSMutableArray *arrayN = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    for (NSDictionary *dic in array) {
        NSDictionary *inv = dic[@"inviter"];
        FriednInviterModel *model = [[FriednInviterModel alloc] init];
        model.gender = [inv[@"gender"]integerValue];
        model.state = [dic[@"status"]integerValue];
        model.nickName = inv[@"nickname"];
        model.userId = [inv[@"id"]integerValue];
        model.invId = [dic[@"id"]integerValue];
        model.timeS = [dic[@"invite_time"]integerValue];
        model.imagePathUrlString = inv[@"portrait"];
        NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
        [stampFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        //以 1970/01/01 GMT为基准，然后过了secs秒的时间
        NSDate *invTime = [NSDate dateWithTimeIntervalSince1970:[dic[@"invite_time"]integerValue]];
        model.lastInvTime = [invTime dateToString];
        NSInteger inviter_id = [dic[@"inviter_id"]integerValue];
        if (![arrayN containsObject:StrByInt(inviter_id)]) {
            [arrayN addObject:StrByInt(inviter_id)];
            [_dataArray addObject:model];
        }
    }
    [_tableView reloadData];
}

- (void)updateFriendRequest {
    DEF_WEAKSELF_(FriendRequestTb)
    [SN_Net friendGetInvitationSuccess:^(id object) {
        NSArray *array = object;
        if (array) {
            [weakSelf updateUIViewWith:array];
        }
    } fail:^(id object) {
    }];
}

@end
